package com.ezandroid.module.network.request;

import android.text.TextUtils;

import com.ezandroid.library.network.util.GsonUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 封装Gson Request
 *
 * @author markmjw
 * @date 2014-11-06
 */
public abstract class HttpGsonRequest<T> extends HttpBaseRequest<T> {

    public HttpGsonRequest(String url) {
        super(url);
    }

    public HttpGsonRequest(String url, String nodeName) {
        super(url, nodeName);
    }

    public HttpGsonRequest(int method, String url, String nodeName) {
        super(method, url, nodeName);
    }

    @Override
    protected T parseResponse(String content, JSONObject json) throws JSONException {
        // 解析数据体
        Type type = ((ParameterizedType) ((Object) this).getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
        T model = null;
        if (!TextUtils.isEmpty(mNodeName)) {
            if (null != json) {
                String data = json.optString(mNodeName, content);
                if (!TextUtils.isEmpty(data)) {
                    model = GsonUtil.fromJson(data, type);
                }
            }
        } else {
            model = GsonUtil.fromJson(content, type);
        }
        return model;
    }
}